package screen.component
{
	import com.adobe.serialization.json.JSON;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.text.TextField;
	
	import helper.Services;
	import helper.ValueObject;
	
	import screen.SacombankScreen;

	/**
	 * ...
	 * @author ...
	 */
	public class Resource extends UI
	{
		private var _control_left_mc : MovieClip;
		public static var instance:Resource;
		private var _service:Services;
		private var _resource_loader:URLLoader;
		private var _header_mc:MovieClip;
		
		public function Resource() 
		{
			if(!instance){
				instance = this;
			}			
			init();
		}
		public static function getInstance(): Resource{
			if(!instance){
				instance = new Resource();
			}
			return instance;
		}
		public function init():void {
			_control_left_mc = SacombankScreen.instance.getControl_left;
			_header_mc = SacombankScreen.instance.getHeader;
			_service = Services.getInstance();
			_resource_loader = new URLLoader();
			showResource();
		}
		private function showResource():void {
			_resource_loader.addEventListener(Event.COMPLETE,getResourceComplete);
			_resource_loader.addEventListener(IOErrorEvent.IO_ERROR,getResourceError);
			_resource_loader.load(_service.getResourceRequest());
		}
		private function getResourceComplete(e:Event):void{
			_resource_loader.removeEventListener(Event.COMPLETE,getResourceComplete);
			_resource_loader.removeEventListener(IOErrorEvent.IO_ERROR, getResourceError);
			ValueObject._info_player = JSON.decode(e.target.data);
			TextField(_control_left_mc.startTf).text = "" + ValueObject._info_player.star;
			TextField(_control_left_mc.goldTf).text = "" + ValueObject._info_player.gold;
			TextField(_header_mc.userNameTf).text = ""+ValueObject._info_player.name;
		}
		public function addGold(gold:Number):void{
			ValueObject._info_player.gold = Number(ValueObject._info_player.gold) + gold;
			TextField(_control_left_mc.goldTf).text = ""+ValueObject._info_player.gold;
		}
		public function reduceGold(gold:Number):void{
			ValueObject._info_player.gold = Number(ValueObject._info_player.gold) - gold;
			TextField(_control_left_mc.goldTf).text = "" + ValueObject._info_player.gold;
		}
		public function addStar(star:Number):void{
			ValueObject._info_player.star = Number(ValueObject._info_player.star) + star;
			TextField(_control_left_mc.startTf).text = "" + ValueObject._info_player.star;
		}
		public function reduceStar(star:Number):void{
			
		}
		private function getResourceError(e:IOErrorEvent):void{
			_resource_loader.removeEventListener(Event.COMPLETE,getResourceComplete);
			_resource_loader.removeEventListener(IOErrorEvent.IO_ERROR, getResourceError);
		}
	}

}